package com.wudgaby.study.jwtauth.config;

import com.wudgaby.study.jwtauth.util.BeanValidators;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.validation.Validator;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.time.Duration;

@Configuration
@ConfigurationProperties(prefix = "jwt")
@Data
@Slf4j
public class TokenProperties implements InitializingBean {
    @Autowired
    private Validator validator;

    @NotBlank(message = "jwt密钥不能为空")
    @Length(min = 50, message = "jwt密钥长度必须大于50")
    private String secretKey;
    @NotNull(message = "加密算法不能为空")
    private SignatureAlgorithm signatureAlgorithm;

    @NotNull(message = "访问token过期时间不能为空")
    private Duration accessTokenExpire;
    @NotNull(message = "刷新token过期时间不能为空")
    private Duration refreshTokenExpire;

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("校验token properties.");
        BeanValidators.validateWithException(validator, this);

        if(accessTokenExpire.getSeconds() >= refreshTokenExpire.getSeconds()){
            throw new IllegalArgumentException("accessTokenExpire 必须小于 refreshTokenExpire");
        }
    }
}
